package com.yungee.lock;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

public class MemoryLock {
    private static final Map<String, String> MEM_LOCK_MAP = new ConcurrentHashMap();
    private static final int MAP_MAX_LEN = 2000;

    public MemoryLock() {
    }

    public static boolean tryLock(String key) {
        if (key == null) {
            return false;
        } else if (MEM_LOCK_MAP.containsKey(key)) {
            return false;
        } else {
            MEM_LOCK_MAP.put(key, key);
            return true;
        }
    }

    public static void unlock(String key) {
        if (key != null && MEM_LOCK_MAP.containsKey(key)) {
            MEM_LOCK_MAP.remove(key);
        }

        if (MEM_LOCK_MAP.size() > 2000) {
            MEM_LOCK_MAP.clear();
        }

    }
}
